package com.ruoyi.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.pay.entity.Commodity;
import com.ruoyi.pay.entity.OrderInfo;
import com.ruoyi.pay.enums.OrderStatus;
import com.ruoyi.pay.mapper.CommodityMapper;
import com.ruoyi.pay.mapper.OrderInfoMapper;
import com.ruoyi.pay.service.OrderInfoService;
import com.ruoyi.pay.utils.OrderNoUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.ruoyi.common.utils.SecurityUtils.getUserId;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Resource
    private CommodityMapper commodityMapper;

    @Resource
    private OrderInfoMapper orderInfoMapper;

    @Override
    public OrderInfo createOrderInfo(Long commodityId) {
        // 获取商品信息
        Commodity commodity = commodityMapper.selectById(commodityId);

        // 生成订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setTitle(commodity.getTitle());
        orderInfo.setOrderNo(OrderNoUtils.getOrderNo());    // 订单号
        orderInfo.setUserId(getUserId());
        orderInfo.setProductId(commodity.getId());
        orderInfo.setTotalFee(commodity.getPrice());
        orderInfo.setOrderStatus(OrderStatus.NOTPAY.getStatus());

        // 存入数据库
        int insert = orderInfoMapper.insert(orderInfo);

        if(insert < 1)
            throw new RuntimeException("插入订单数据失败");

        return orderInfo;
    }

    @Override
    public OrderInfo selectByOrderNo(String outTradeNo) {
        LambdaQueryWrapper<OrderInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo, outTradeNo);

        return orderInfoMapper.selectOne(wrapper);
    }

    @Override
    public void updateOrderStatus(String orderNo,String status) {
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderInfo::getOrderNo, orderNo);
        wrapper.set(OrderInfo::getOrderStatus, status);
        int update = orderInfoMapper.update(null, wrapper);
        if(update < 1)
            throw new RuntimeException("更新订单状态失败");
    }
}
